package demo;

import java.util.concurrent.CountDownLatch;

public class leetcode1114 {

    // 用于控制顺序
    private CountDownLatch secondLatch = new CountDownLatch(1);
    private CountDownLatch thirdLatch = new CountDownLatch(1);

    public void first() {
        // 执行 first 操作
        System.out.println("first");
        // first 执行完成，释放 second 的等待
        secondLatch.countDown();
    }

    public void second() throws InterruptedException {
        // 等待 first 完成
        secondLatch.await();
        // 执行 second 操作
        System.out.println("second");
        // second 执行完成，释放 third 的等待
        thirdLatch.countDown();
    }

    public void third() throws InterruptedException {
        // 等待 second 完成
        thirdLatch.await();
        // 执行 third 操作
        System.out.println("third");
    }

    public static void main(String[] args) {
        leetcode1114 foo = new leetcode1114();

        // 三个线程分别调用 first、second、third
        Thread threadA = new Thread(() -> foo.first());
        Thread threadB = new Thread(() -> {
            try {
                foo.second();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread threadC = new Thread(() -> {
            try {
                foo.third();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 可以随机启动线程
        threadC.start();
        threadB.start();
        threadA.start();
    }
}
